package com.jhoncy.rapid.base.service.serviceImpl;

import com.jhoncy.rapid.base.bean.UserInfo;
import com.jhoncy.rapid.base.bo.BasePermissionTypeEnum;
import com.jhoncy.rapid.base.pojo.BasePermission;
import com.jhoncy.rapid.base.repository.BasePermissionRepository;
import com.jhoncy.rapid.base.service.BasePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhuangqi
 * @date 2017/7/27.
 */
@Service
public class BasePermissionServiceImpl implements BasePermissionService{

    @Autowired
    private BasePermissionRepository basePermissionRepository;

    @Override
    public List<BasePermission> listByUserIdAndType(String userId, String typeName) {
        List<BasePermission> permissions = basePermissionRepository.
                findBasePermissionsByUserIdAndType(userId, BasePermissionTypeEnum.AUTH.name());
        return permissions;
    }


    @Override
    public List<BasePermission> listMenus() {
        List<BasePermission> menus = basePermissionRepository.
                findBasePermissionsByUserIdAndType(UserInfo.getUserId(),BasePermissionTypeEnum.MENU.name());
        menus = listMenu2Tree(menus);
        return menus;
    }

    /**
     * 无排序菜单列表->树形菜单树
     * @param menus
     * @return
     */
    private List<BasePermission> listMenu2Tree(List<BasePermission> menus) {
        List<BasePermission> menuTree = new ArrayList<>();
        Map<String,BasePermission> snap = menus.stream().collect(Collectors.toMap(BasePermission::getPermissionId,t->t));
        snap.forEach((key, value) -> {
            BasePermission parentMenu = snap.get(value.getParentId());
            if (parentMenu != null)
                snap.get(value.getParentId()).getChildren().add(value);
            else
                menuTree.add(value);
        });
        menuSort(menuTree);
        return menuTree;
    }

    private void menuSort(List<BasePermission> menus) {
        for (BasePermission menu : menus) {
            if (menu.getChildren().size()>0) menuSort(menu.getChildren());
        }
        menus.sort(Comparator.comparingInt(BasePermission::getOrderNum));
    }
}
